import * as path from "path";
import * as vscode from "vscode";
import * as fs from "fs";

// 获取一个editor的相对路径
export const getRelativePath = (editor: vscode.TextEditor) => {
  const workspaceFolders = vscode.workspace.workspaceFolders;
  if (workspaceFolders) {
    const filePath = editor.document.uri.fsPath;
    const relativePath = vscode.workspace.asRelativePath(filePath);

    return relativePath; // 相对于工作区的路径
  }

  return "";
};

// TODO7：点击提交后替换文案
export function replaceTextInEditor(
  editor: vscode.TextEditor,
  wordRange: vscode.Range,
  key: string
) {
  if (!editor) return;

  // const edit = new vscode.WorkspaceEdit();
  // const { document } = editor;

  // edit.replace(document.uri, wordRange, key);

  // vscode.workspace.applyEdit(edit);
}

// 在对应目录下创建翻译key文件
export async function createTranslationFiles(
  key: string,
  zh: string,
  en: string
) {
  // 获取工作区路径
  const workspacePath = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
  if (!workspacePath) {
    throw new Error("No workspace is open.");
  }
  const basePath = path.join(workspacePath, "src/i18n/langs");
  const zhCNPath = path.join(basePath, "zh_CN");
  const enUSPath = path.join(basePath, "en_US");

  const keyParts = key.split(".").slice(1); // 移除前缀 'I18N'
  const moduleName = keyParts[0];
  const propPath = keyParts.slice(1);

  if (!moduleName || propPath.length === 0) {
    throw new Error("Invalid key format.");
  }

  await updateModuleFile(zhCNPath, moduleName, propPath, zh);
  await updateModuleFile(enUSPath, moduleName, propPath, en);
  await updateIndexFile(zhCNPath, moduleName);
  await updateIndexFile(enUSPath, moduleName);
}

// 更新模块文件
async function updateModuleFile(
  dirPath: string,
  moduleName: string,
  propPath: string[],
  value: string
) {
  const filePath = path.join(dirPath, `${moduleName}.ts`);
  let moduleContent = {};

  if (fs.existsSync(filePath)) {
    const content = fs.readFileSync(filePath, "utf-8");
    const match = content.match(/const\s+\w+\s*=\s*(\{[\s\S]*?\});/);
    if (match) {
      moduleContent = JSON.parse(match[1]);
    }
  }

  let ref: any = moduleContent;
  propPath.forEach((prop, index) => {
    if (!ref[prop]) {
      ref[prop] = {};
    }
    if (index === propPath.length - 1) {
      ref[prop] = value;
    }
    ref = ref[prop];
  });

  const newContent = `const ${moduleName} = ${JSON.stringify(
    moduleContent,
    null,
    2
  )};\nexport default ${moduleName};`;
  await fs.promises.mkdir(path.dirname(filePath), { recursive: true });
  await fs.promises.writeFile(filePath, newContent);
}

// 更新index.ts文件
async function updateIndexFile(dirPath: string, moduleName: string) {
  const indexPath = path.join(dirPath, `index.ts`);
  const files = fs.readdirSync(dirPath);

  let importStatements = "";
  let moduleEntries: string[] = [];

  files.forEach((file) => {
    const moduleName = path.basename(file, ".ts");
    if (moduleName !== "index") {
      importStatements += `import ${moduleName} from './${moduleName}';\n`;
      moduleEntries.push(`  ${moduleName}: {\n    ...${moduleName},\n  }`);
    }
  });

  const exportI18NStatement = `\
  const I18N = {
  ${moduleEntries.join(",\n")}
  };
  
  export default I18N;
  `;

  const indexContent = `${importStatements.trim()}\n\n${exportI18NStatement.trim()}\n`;

  await fs.promises.writeFile(indexPath, indexContent);
}
